using System;
using System.Collections.Generic;
using System.Text;
using ScrewTurn.Wiki.PluginFramework;
using System.Text.RegularExpressions;

namespace Stankovski.Wiki.FormattingPlus
{
	public abstract class FormatterPlusBase : IFormatterProviderV30
	{
		protected IHostV30 host;
		protected string config;
		private static Regex noWiki = new Regex(@"\<nowiki\>(.|\n|\r)+?\<\/nowiki\>", RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);

		public bool PerformPhase1
		{
			get { return true; }
		}

		public bool PerformPhase2
		{
			get { return true; }
		}

		public bool PerformPhase3
		{
			get { return true; }
		}

		public abstract string Format(string raw, ContextInformation context, FormattingPhase phase);

		public void Init(IHostV30 host, string config)
		{
			this.host = host;
			this.config = config;
		}

		public void Shutdown()
		{
			// DO NOTHING
		}

		public ComponentInformation Information
		{
			get { 
				return new ComponentInformation(this.GetType().Name, "Denis Stankovski", "1.0", "http://www.bah.com", null);
			}
		}

		protected static void ComputeNoWiki(string text, ref List<int> noWikiBegin, ref List<int> noWikiEnd)
		{
			Match match;
			noWikiBegin.Clear();
			noWikiEnd.Clear();

			match = noWiki.Match(text);
			while (match.Success)
			{
				noWikiBegin.Add(match.Index);
				noWikiEnd.Add(match.Index + match.Length);
				match = noWiki.Match(text, match.Index + match.Length);
			}
		}

		protected static bool IsNoWikied(int index, List<int> noWikiBegin, List<int> noWikiEnd, out int end)
		{
			for (int i = 0; i < noWikiBegin.Count; i++)
			{
				if (index > noWikiBegin[i] && index < noWikiEnd[i])
				{
					end = noWikiEnd[i];
					return true;
				}
			}
			end = 0;
			return false;
		}

		public int ExecutionPriority
		{
			get { return 50; }
		}

		public string PrepareTitle(string title, ContextInformation context)
		{
			return title;
		}

		
		public string ConfigHelpHtml
		{
			get { return "No configuration is required."; }
		}		
	}
}
